package com.caigou.modules.article.ui.fragment

import android.os.Bundle
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.viewModels
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.launcher.ARouter
import com.caigou.comm.base.bean.AppBackgroundInfo
import com.caigou.comm.base.bean.CommentBean
import com.caigou.comm.base.bus.BusKey
import com.caigou.comm.base.bus.LiveDataBus
import com.caigou.comm.base.constants.AppConstants
import com.caigou.comm.base.constants.RouterPath
import com.caigou.comm.base.container.BaseFragment
import com.caigou.comm.base.ext.Resource
import com.caigou.comm.base.ext.observe
import com.caigou.comm.base.ext.showToast
import com.caigou.comm.base.viewmodel.ReportViewModel
import com.caigou.comm.base.widget.ReportDialog
import com.caigou.comm.base.widget.SpaceItemDecoration
import com.caigou.modules.article.R
import com.caigou.modules.article.adpter.ArticleCommentItemAdapter
import com.caigou.modules.article.databinding.FragmentCommentBinding
import com.caigou.modules.article.ui.ArticleActivity
import com.caigou.modules.article.viewmodel.CommentViewModel
import com.caigou.modules.article.viewmodel.LikeViewModel
import dagger.hilt.android.AndroidEntryPoint

/**
 * @author #Suyghur.
 * Created on 2021/11/22
 */
@AndroidEntryPoint
class ArticleCommentFragment : BaseFragment() {

    private var _binding: FragmentCommentBinding? = null
    private val binding get() = _binding!!

    private val commentViewModel: CommentViewModel by viewModels()
    private val likeViewModel: LikeViewModel by viewModels()
    private val reportViewModel: ReportViewModel by viewModels()

    private var page = 1
    private val limit = 10
    private var totalPage = 0
    private var sort = 0

    private val mAdapter: ArticleCommentItemAdapter by lazy {
        ArticleCommentItemAdapter(requireActivity(), mutableListOf())
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        _binding = FragmentCommentBinding.inflate(inflater, container, false)
        return _binding?.root
    }

    override fun initView() {
        mAdapter.loadMoreModule.run {
            setOnLoadMoreListener {
                mAdapter.loadMoreModule.isEnableLoadMore = true
                fetchCommentList()
            }
            isAutoLoadMore = true
            isEnableLoadMoreIfNotFullPage = false
        }
        binding.commentRecyclerView.run {
            layoutManager = LinearLayoutManager(requireActivity())
            adapter = mAdapter
            itemAnimator = DefaultItemAnimator()
            addItemDecoration(SpaceItemDecoration(requireActivity()))
        }

        mAdapter.setOnItemChildClickListener { _, view, position ->
            val item = mAdapter.data[position]
            when (view.id) {
                R.id.item_comment_iv_avatar -> {
                    ARouter.getInstance().build(RouterPath.Personal.PAGE_PERSONAL_PAGE)
                        .withString(AppConstants.USER_ID, item.replyUserInfoVo.userId)
                        .navigation()
                }
                R.id.item_comment_ll_content -> {
                    ARouter.getInstance().build(RouterPath.Article.PAGE_COMMENT_DETAIL)
                        .withObject(AppConstants.COMMENT_ITEM_BEAN, item)
                        .navigation()
                }
                R.id.item_comment_iv_like -> {
                    if (AppBackgroundInfo.instance.hasLogin) {
                        if (item.like) {
                            showToast("您已经点过赞了")
                        } else {
                            likeViewModel.setCommentLike(item.replyId, AppBackgroundInfo.instance.userBean!!.userId, item.replyUserInfoVo.userId)
                        }
                    } else {
                        ARouter.getInstance().build(RouterPath.Login.PAGE_LOGIN).navigation()
                    }
                }
                R.id.item_comment_btn_reply -> {
                    if (AppBackgroundInfo.instance.hasLogin) {
                        ARouter.getInstance()
                            .build(RouterPath.Article.PAGE_COMMENT_REPLY)
                            .withObject(AppConstants.COMMENT_ITEM_BEAN, item)
                            .withObject(AppConstants.COMMENT_ROOT_ITEM_BEAN, item)
                            .navigation()
                    } else {
                        ARouter.getInstance().build(RouterPath.Login.PAGE_LOGIN).navigation()
                    }
                }
                R.id.item_comment_btn_reply -> {
                    if (AppBackgroundInfo.instance.hasLogin) {
                        with(ReportDialog(requireActivity())) {
                            btnConfirm.setOnClickListener {
                                if (TextUtils.isEmpty(reportCause)) {
                                    showToast("举报原因不能为空！")
                                    return@setOnClickListener
                                }
                                reportViewModel.setReplyReport(
                                    AppBackgroundInfo.instance.userBean!!.userId, item.replyUserInfoVo.userId,
                                    reportCause, item.replyId, 3
                                )
                                dismiss()
                            }
                            show()
                        }
                    } else {
                        ARouter.getInstance().build(RouterPath.Login.PAGE_LOGIN).navigation()
                    }
                }
                R.id.item_comment_iv_report->{
                    if (AppBackgroundInfo.instance.hasLogin) {
                        with(ReportDialog(requireActivity())) {
                            btnConfirm.setOnClickListener {
                                if (TextUtils.isEmpty(reportCause)) {
                                    showToast("举报原因不能为空！")
                                    return@setOnClickListener
                                }
                                reportViewModel.setReplyReport(
                                    AppBackgroundInfo.instance.userBean!!.userId, item.replyUserInfoVo.userId,
                                    reportCause, item.replyId, 3
                                )
                                dismiss()
                            }
                            show()
                        }
                    } else {
                        ARouter.getInstance().build(RouterPath.Login.PAGE_LOGIN).navigation()
                    }
                }
            }
        }

        binding.commentRgSelector.setOnCheckedChangeListener { group, _ ->
            sort = when (group.checkedRadioButtonId) {
                binding.commentBtnSequential.id -> 1
                binding.commentBtnReverse.id -> 0
                else -> 0
            }
            page = 1
            totalPage = 0
            fetchCommentList()
        }
    }

    override fun lazyLoad() {
        fetchCommentList()
    }

    override fun onBack() {
    }

    override fun observeViewModel() {
        observe(commentViewModel.commentListLiveData, ::handleGetCommentList)
        observe(likeViewModel.commentLikeLiveData, ::handleSetCommentLike)
        observe(reportViewModel.replyReportLiveData, ::handleSetReport)
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }

    private fun handleGetCommentList(result: Resource<CommentBean>) {
        when (result) {
            is Resource.Loading -> {
                mDialog.show()
            }
            is Resource.DataError -> {
                mDialog.dismiss()
                if (!TextUtils.isEmpty(result.errorMsg)) {
                    showToast(result.errorMsg)
                } else {
                    showToast("获取评论信息异常")
                }
            }
            is Resource.Success -> {
                mDialog.dismiss()
                mAdapter.loadMoreModule.isEnableLoadMore = true

                if (result.data == null) {
                    binding.commentLlEmpty.visibility = View.VISIBLE
                    binding.commentRecyclerView.visibility = View.GONE
                    return
                }

                if (result.data!!.list.isNullOrEmpty()) {
                    binding.commentLlEmpty.visibility = View.VISIBLE
                    binding.commentRecyclerView.visibility = View.GONE
                } else {
                    binding.commentLlEmpty.visibility = View.GONE
                    binding.commentRecyclerView.visibility = View.VISIBLE
                }

                totalPage = result.data!!.totalPage

                if (page == 1) {
                    mAdapter.setList(result.data!!.list)
                } else {
                    mAdapter.addData(result.data!!.list)
                }

                if (result.data!!.pageSize < limit) {
                    mAdapter.loadMoreModule.loadMoreEnd(false)
                } else {
                    mAdapter.loadMoreModule.loadMoreComplete()
                }

                if (page >= totalPage) {
                    mAdapter.loadMoreModule.loadMoreEnd(false)
                } else {
                    page++
                }
                LiveDataBus.get().with(BusKey.LOAD_VP2_FINISH).value = Any()
            }
        }
    }

    private fun handleSetCommentLike(result: Resource<String>) {
        when (result) {
            is Resource.Loading -> {
                mDialog.show()
            }
            is Resource.DataError -> {
                mDialog.dismiss()
                if (!TextUtils.isEmpty(result.errorMsg)) {
                    showToast(result.errorMsg)
                } else {
                    showToast("点赞失败，请稍后再试")
                }
            }
            is Resource.Success -> {
                mDialog.dismiss()
                if (result.data != null) {
                    showToast(result.data!!)
                    fetchCommentList()
                }
            }
        }
    }

    private fun handleSetReport(result: Resource<String>) {
        when (result) {
            is Resource.Loading -> {
                mDialog.show()
            }
            is Resource.DataError -> {
                mDialog.dismiss()
                if (!TextUtils.isEmpty(result.errorMsg)) {
                    showToast(result.errorMsg)
                } else {
                    showToast("举报异常")
                }
            }
            is Resource.Success -> {
                mDialog.dismiss()
                if (result.data == null) {
                    return
                }
                showToast(result.data!!)
            }
        }
    }

    private fun fetchCommentList() {
        if (AppBackgroundInfo.instance.hasLogin) {
            commentViewModel.getCommentList(page, limit, AppBackgroundInfo.instance.userBean!!.userId, (requireActivity() as ArticleActivity).dataId, sort)
        } else {
            commentViewModel.getCommentList(page, limit, "", (requireActivity() as ArticleActivity).dataId, sort)
        }
    }

    fun loadCommentList() {
        page = 1
        totalPage = 0
        fetchCommentList()
    }
}